package ru.bragnikita.utils.logexplorer.model;

import ru.bragnikita.utils.logexplorer.web.ConvertationUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author Nikita.Brazhnikov
 */
public class FsItem {

	private static final long MAX_EDITABLE_SIZE = 1024 * 500; //500Kb

	private String absolutePath;
	private String name;
	private boolean isDirectory;
	private Date lastModified;
	private long size;
	private File file;
	private String safeFileId;
	private boolean isEditable = false;
	private boolean isExecutable = false;

	public FsItem(File file) {
		this.file = file;
		this.lastModified = new Date(file.lastModified());
		this.size = file.length();
		this.isDirectory = file.isDirectory();
		try {
			safeFileId = URLEncoder.encode(file.getAbsolutePath(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		isEditable = !isDirectory() && size <= MAX_EDITABLE_SIZE;
		isExecutable = ConvertationUtils.isExecutable(file.getAbsolutePath());
	}

	public String getAbsolutePath() {
		return absolutePath;
	}

	public String getSafeFileId() {
		return safeFileId;
	}

	public boolean isExecutable() {
		return isExecutable;
	}

	public void setAbsolutePath(String absolutePath) {
		this.absolutePath = absolutePath;
	}

	public boolean isDirectory() {
		return isDirectory;
	}

	public void setDirectory(boolean directory) {
		isDirectory = directory;
	}

	public String getName() {
		return name;
	}

	public boolean isEditable() {
		return isEditable;
	}

	public void setName(String name) {
		this.name = name;
	}

	public File getFile() {
		return file;
	}

	public Date getLastModified() {
		return lastModified;
	}

	public long getSize() {
		return size;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof FsItem)) return false;

		FsItem fsItem = (FsItem) o;

		if (!absolutePath.equals(fsItem.absolutePath)) return false;

		return true;
	}

	@Override
	public int hashCode() {
		return absolutePath.hashCode();
	}
}
